<template>
  <div class="genealogy-container">
    <!-- 页面头部 -->
    <a-card class="header-card" :bordered="false">
      <a-space :size="16" align="center" style="margin-bottom: 16px;">
        <a-avatar :size="48" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
          <template #icon>
            <ApartmentOutlined />
          </template>
        </a-avatar>
        <div class="page-title">专利谱系分析</div>
        <div class="page-subtitle">可视化展示专利之间的关系与演进</div>
      </a-space>
      
      <div>
        <a-space :size="12">
          <a-button type="primary" @click="loadTreeData" :loading="treeLoading" size="large">
            加载数据
          </a-button>
          <a-button @click="handleExpandAll" :disabled="!tree.length" size="large">
            展开全部
          </a-button>
          <a-button @click="handleCollapseAll" :disabled="!tree.length" size="large">
            收起全部
          </a-button>
        </a-space>
      </div>
    </a-card>

    <!-- 统计信息卡片 -->
    <a-row :gutter="16" v-if="tree.length > 0" style="margin-top: 16px;">
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-content">
            <ApartmentOutlined class="stat-icon" style="color: #667eea; font-size: 32px;" />
            <div class="stat-info">
              <div class="stat-value" style="color: #667eea;">{{ treeStats.totalNodes }}</div>
              <div class="stat-label">专利节点总数</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-content">
            <BranchesOutlined class="stat-icon" style="color: #f5576c; font-size: 32px;" />
            <div class="stat-info">
              <div class="stat-value" style="color: #f5576c;">{{ treeStats.maxDepth }}</div>
              <div class="stat-label">最大层级深度</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-content">
            <ForkOutlined class="stat-icon" style="color: #00a8ff; font-size: 32px;" />
            <div class="stat-info">
              <div class="stat-value" style="color: #00a8ff;">{{ treeStats.rootNodes }}</div>
              <div class="stat-label">根节点数量</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <div class="stat-content">
            <FileTextOutlined class="stat-icon" style="color: #38d39f; font-size: 32px;" />
            <div class="stat-info">
              <div class="stat-value" style="color: #38d39f;">{{ treeStats.leafNodes }}</div>
              <div class="stat-label">叶子节点数量</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 树形展示区域 -->
    <a-card class="tree-card" :bordered="false" style="margin-top: 16px;">
      <template #title>
        <a-space>
          <ClusterOutlined style="font-size: 18px; color: #1890ff;" />
          <span style="font-size: 16px; font-weight: 600;">谱系树形结构</span>
        </a-space>
      </template>

      <a-spin :spinning="treeLoading" tip="正在加载谱系数据，请稍候..." size="large">
        <a-empty 
          v-if="tree.length === 0 && !treeLoading" 
          description="暂无谱系数据"
          :image="Empty.PRESENTED_IMAGE_SIMPLE"
        >
          <a-button type="primary" @click="loadTreeData">
            <template #icon><ReloadOutlined /></template>
            点击加载数据
          </a-button>
        </a-empty>

        <div v-else class="tree-wrapper">
          <BasicTree 
            ref="asyncExpandTreeRef" 
            :treeData="tree"
            :showLine="true"
            defaultExpandAll
          />
        </div>
      </a-spin>
    </a-card>
  </div>
</template>

<script setup lang="ts" name="patent-analysis-genealogy-TreeIndex">
  import { BasicTree, TreeActionType, TreeItem } from '@/components/Tree';
  import { ref, unref, computed } from 'vue';
  import { loadTree } from './Genealogy.api';
  import message from 'ant-design-vue/es/message';
  import Empty from 'ant-design-vue/es/empty';
  import {
    ApartmentOutlined,
    ReloadOutlined,
    DownSquareOutlined,
    UpSquareOutlined,
    BranchesOutlined,
    ForkOutlined,
    FileTextOutlined,
    ClusterOutlined,
  } from '@ant-design/icons-vue';

  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const treeLoading = ref(false);
  const tree = ref<TreeItem[]>([]);

  // 计算树的统计信息
  const treeStats = computed(() => {
    const stats = {
      totalNodes: 0,
      maxDepth: 0,
      rootNodes: 0,
      leafNodes: 0,
    };

    const traverse = (nodes: TreeItem[], depth: number = 1) => {
      if (!nodes || nodes.length === 0) return;
      
      nodes.forEach(node => {
        stats.totalNodes++;
        stats.maxDepth = Math.max(stats.maxDepth, depth);
        
        if (depth === 1) stats.rootNodes++;
        if (!node.children || node.children.length === 0) stats.leafNodes++;
        
        if (node.children && node.children.length > 0) {
          traverse(node.children, depth + 1);
        }
      });
    };

    traverse(tree.value);
    return stats;
  });

  async function loadTreeData() {
    try {
      treeLoading.value = true;
      let data = await loadTree();
      tree.value = data || [];
      
      if (data && data.length > 0) {
        message.success(`成功加载 ${treeStats.value.totalNodes} 个节点`);
        setTimeout(() => {
          unref(asyncExpandTreeRef)?.expandAll(true);
        }, 100);
      } else {
        message.info('暂无谱系数据');
      }
    } catch (error) {
      message.error('加载数据失败，请重试');
      console.error('加载谱系数据失败:', error);
    } finally {
      treeLoading.value = false;
    }
  }

  function handleExpandAll() {
    unref(asyncExpandTreeRef)?.expandAll(true);
    message.success('已展开全部节点');
  }

  function handleCollapseAll() {
    unref(asyncExpandTreeRef)?.expandAll(false);
    message.success('已收起全部节点');
  }
</script>

<style scoped lang="less">
.genealogy-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 100px);

  // 页面头部卡片
  .header-card {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    background: #fff;

    :deep(.ant-card-body) {
      padding: 20px 24px;
    }

    .page-title {
      font-size: 20px;
      font-weight: 600;
      color: #262626;
      line-height: 1.4;
    }

    .page-subtitle {
      font-size: 14px;
      color: #8c8c8c;
      margin-top: 4px;
    }
  }

  // 统计卡片
  .stat-card {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    cursor: default;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
    }

    :deep(.ant-card-body) {
      padding: 20px;
    }

    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        flex-shrink: 0;
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 28px;
          font-weight: 600;
          line-height: 1.2;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: #8c8c8c;
        }
      }
    }
  }

  // 树形卡片
  .tree-card {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    :deep(.ant-card-head) {
      border-bottom: 1px solid #f0f0f0;
      padding: 16px 24px;
    }

    :deep(.ant-card-body) {
      padding: 24px;
      min-height: 400px;
    }

    // 树形包装器
    .tree-wrapper {
      :deep(.ant-tree) {
        background: transparent;
        
        .ant-tree-treenode {
          padding: 4px 0;
          transition: all 0.3s ease;

          &:hover {
            background: #f5f7fa;
            border-radius: 6px;
          }
        }

        .ant-tree-node-content-wrapper {
          padding: 6px 12px;
          border-radius: 6px;
          transition: all 0.2s ease;

          &:hover {
            background: #e6f7ff !important;
          }

          &.ant-tree-node-selected {
            background: #bae7ff !important;
          }
        }

        .ant-tree-switcher {
          color: #1890ff;
        }

        .ant-tree-iconEle {
          font-size: 16px;
        }
      }
    }
  }

  // 加载动画优化
  :deep(.ant-spin-nested-loading) {
    min-height: 300px;
  }

  :deep(.ant-spin-text) {
    color: #1890ff;
    font-size: 14px;
    padding-top: 8px;
  }

  :deep(.ant-spin-dot) {
    font-size: 32px;
  }
}
</style>
